package com.yj.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

public class UpLoad {

	private static final Logger LOGGER = LoggerFactory.getLogger(UpLoad.class);

	public static String upload(MultipartFile file) {
		if (file.isEmpty()) {
			System.out.println("上传失败，请选择文件");
		}

		String fileName = file.getOriginalFilename();
		String filePath = "E:\\项目二\\";
		File dest = new File(filePath + fileName);
		try {
			file.transferTo(dest);
			LOGGER.info("上传成功");
			System.out.println("上传成功");
		} catch (IOException e) {
			LOGGER.error(e.toString(), e);
		}
		System.out.println("上传失败！");
		return fileName;
	}

	public static String multiUpload(List<MultipartFile> files) {
//		List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
		Map<String,String> imgs = new HashMap<String,String>();
		String filePath = "E:\\项目二\\";
//		System.out.println(files.size());//上传的文件个数
		for (int i = 0; i < files.size(); i++) {
			MultipartFile file = files.get(i);
			if (file.isEmpty()) {
				System.out.println("第" + (i + 1) + "个文件没有");
			}else {
			String fileName = file.getOriginalFilename();// 文件名
			imgs.put("img"+(i+1), fileName);
			File dest = new File(filePath + fileName);
			try {
				file.transferTo(dest);
				LOGGER.info("第" + (i + 1) + "个文件上传成功");
			} catch (IOException e) {
				LOGGER.error(e.toString(), e);
				System.out.println("上传第" + (i++) + "个文件失败");
			}
			}
		}
		String json = JSONObject.toJSONString(imgs);
		return json;

	}

}
